package com.cainaer.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cainaer.common.core.utils.*;
import com.cainaer.common.redis.service.RedisService;
import com.cainaer.member.domain.Member;
import com.cainaer.member.domain.vo.MemberVo;
import com.cainaer.member.domain.vo.Sign;
import com.cainaer.member.domain.MemberInfo;
import com.cainaer.member.mapper.MemberInfoMapper;
import com.cainaer.member.mapper.MemberMapper;
import com.cainaer.member.service.IMemberService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 会员登录表 服务实现类
 * </p>
 *
 * @author Tina
 * @since 2020-08-22
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    private Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    /**
     * 标识 实现方法
     * <p>
     * 首先判断用户是否存在，如果不存在就新增数据
     * 如果存在直接返回
     *
     * @param sign
     * @return
     * @throws IOException
     */
    @Override
    @Transient
    public Sign sign(Sign sign) throws IOException {

        String url = WxUtil.MP_LOGIN_URL + "?appid=" + WxUtil.APP_ID + "&secret=" + WxUtil.SECRET_KEY + "&js_code=" + sign.getCode() + "&grant_type=authorization_code";
        JSONObject jsonObject = HttpClientUtils.doGet(url);

        System.out.println("jsonObject={}" + jsonObject);

        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");

        AbstractWrapper wrapper = new QueryWrapper();
        wrapper.eq("open_id", openid);
        Member selectOne = memberMapper.selectOne(wrapper);

        logger.info("selectOne={}", selectOne);

        JSONObject object = WxUtil.getUserInfo(sign.getTelPhone(), sessionKey, sign.getIv());
        if (!StringUtils.isNull(object)) {
            String phoneNumber = object.getString("phoneNumber");
            logger.info("解密手机号码 phoneNumber={}", phoneNumber);
            sign.setTel(Long.valueOf(phoneNumber));
        }

        if (StringUtils.isNull(selectOne)) {
            Member member = new Member();
            member.setTel(sign.getTel());
            member.setMemberImg(sign.getMemberImg());
            member.setStatus(0);
            member.setOpenId(openid);
            member.setCreateTime(DateUtils.getTime());
            member.setUpdateTime(DateUtils.getTime());
            Integer memberInsert = memberMapper.insert(member);
            logger.info("会员注册insert={}", memberInsert);

            MemberInfo memberInfo = new MemberInfo();
            memberInfo.setMemberId(member.getMemberId());
            memberInfo.setNickName(sign.getNickName());
            memberInfo.setUpdateTime(DateUtils.getTime());
            memberInfo.setMemberLevel(1);
            memberInfo.setCreateTime(DateUtils.getTime());
            Integer insertMemBerInfo = memberInfoMapper.insert(memberInfo);
            sign.setMemberInfo(memberInfo);
            logger.info("insertMemBerInfo={}", insertMemBerInfo);
            if (memberInsert > 0) {
                return sign;
            }
        } else {
            return sign;
        }
        return null;
    }


    /**
     * 根据条件分页查询会员列表
     *
     * @param member
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public IPage<Member> queryMemberInfo(Member member, Integer pageNum, Integer pageSize) {
        Page<Member> iPage = new Page<Member>(pageNum, pageSize);
        IPage<Member> memberList = memberMapper.queryMemberInfo(iPage, member);
        return memberList;
    }

    /**
     * 通过会员ID查询会员信息
     *
     * @param memberId
     * @return
     */
    @Override
    public MemberVo selectMemberById(Integer memberId) {
        return memberMapper.selectMemberById(memberId);
    }
}
